package com.lqg.bookLibrary.adminController;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.common.util.JwtUtils;
import com.lqg.bookLibrary.pojo.Users;
import com.lqg.bookLibrary.service.IUsersService;
import com.lqg.bookLibrary.service.webService.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/manage/user")
public class ManageLoginController {

    @Autowired
    private IUsersService usersService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;


    @PostMapping("/login")
    public JsonResult login(@RequestBody String post,
                            HttpServletResponse response) {

        JSONObject jsonObject = JSON.parseObject(post);
        String username = (String)jsonObject.get("username");
        String password = (String)jsonObject.get("password");

        Users one = usersService.lambdaQuery().eq(Users::getUsername, username).one();

        if (one == null) {
            return JsonResult.error("用户名为空");
        }

        String password1 = one.getPassword();
        boolean matches = passwordEncoder.matches(password, password1);
        if (!matches) {
            return JsonResult.error("密码错误");
        }

        String role = one.getRole();
        for(String s : one.getRole().split(" ")){
            if (s.equals("a")) {

                String token = jwtUtils.generateToken(one.getUserId().toString());
                response.setHeader(jwtUtils.getHeader(), token);
                return JsonResult.success();
            }
        }

        return JsonResult.error("没权限");
    }

}
